﻿using Autoupdate.Common;
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace Autoupdate
{
    public partial class DownloadForm : Form
    {
        public delegate void DoBackgroundWorkEventHandler(object sender, EventArgs e);

        public event DoBackgroundWorkEventHandler DoBackgroundWork;

        readonly string logSecion = "程序更新";

        private DataTable mFileTable;
        private int mLeftCount;

        public DownloadForm(DataTable fileTable)
        {
            InitializeComponent();

            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.DoWork += BackgroundWorker_DoWork;
            backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
            backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;

            mFileTable = fileTable;
            mLeftCount = 5;
        }

        public void ReportProgress(int percentProgress, object userState)
        {
            backgroundWorker.ReportProgress(percentProgress, userState);
            //System.Threading.Thread.Sleep(1000);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                dgvFileList.DataSource = mFileTable;
                foreach (DataGridViewColumn column in dgvFileList.Columns)
                {
                    if (column.Name == SysUpdateFile.Name
                        || column.Name == SysUpdateFile.MD5
                        || column.Name == SysUpdateFile.Status)
                        column.Visible = true;
                    else
                        column.Visible = false;
                    column.SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                dgvFileList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                dgvFileList.Columns[SysUpdateFile.Name].Width = 200;

                dgvFileList.Columns[SysUpdateFile.Name].HeaderText = "文件";
                dgvFileList.Columns[SysUpdateFile.MD5].HeaderText = "MD5值";
                dgvFileList.Columns[SysUpdateFile.Status].HeaderText = "状态";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                Log.WriteError(logSecion, ex.Message + ex.StackTrace);
            }
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            try
            {
                Util.Delay(200);
                panel1.BackColor = Color.LightYellow;
                backgroundWorker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                Log.WriteError(logSecion, ex.Message + ex.StackTrace);
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            try
            {
                timer.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                Log.WriteError(logSecion, ex.Message + ex.StackTrace);
            }
        }

        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                DoBackgroundWork?.Invoke(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                //ExceptionForm.ProcessException("", ex);
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                mFileTable.Rows[e.ProgressPercentage][SysUpdateFile.Status] = e.UserState.ToString();
                dgvFileList.FirstDisplayedScrollingRowIndex = e.ProgressPercentage;
            }
            catch (Exception ex)
            {
                //ExceptionForm.ProcessException("", ex);
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                bool downloadCompleted = true;
                for (int i = 0; i < mFileTable.Rows.Count; ++i)
                {
                    if (string.IsNullOrEmpty(mFileTable.Rows[i][SysUpdateFile.Status].ToString()))
                    {
                        downloadCompleted = false;
                        dgvFileList.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                        dgvFileList.Rows[i].DefaultCellStyle.SelectionBackColor = Color.Red;
                    }
                }
                if (!downloadCompleted)
                {
                    panel1.BackColor = Color.Red;
                    lblStatus.Text = "更新失败";
                    MessageBox.Show("软件更新失败，详见文件列表！",
                        "错误",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return;
                }
                btnOK.Enabled = true;
                panel1.BackColor = Color.LightGreen;
                lblStatus.Text = "更新完成";
                timer.Enabled = true;
            }
            catch (Exception ex)
            {
                //ExceptionForm.ProcessException("", ex);
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            try
            {
                --mLeftCount;
                if (mLeftCount == 0)
                {
                    timer.Enabled = false;
                    btnOK.PerformClick();
                }
                else
                    btnOK.Text = "确定(" + mLeftCount.ToString() + ")";
            }
            catch (Exception ex)
            {
                //ExceptionForm.ProcessException("", ex);
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }
    }
}
